import { defineStore } from 'pinia'
import { useNoticeStore, useChatStore, useAuthStore } from '@/store'

const useUserStore = defineStore('user', {
    state: () => {
        return {
            token: loadToken(),
            userInfo: loadUserInfo(),
            config: loadConfigStorage(),
            username: '',
            password: '',
            ywyInfo: '',
            detail: undefined
        }
    },
    actions: {
        /** 初始化 user store 数据*/
        init() {
            // console.log('获取 storage中 保存的数据: --------')
            // console.log('loadUserInfo(): ' + JSON.stringify(loadUserInfo()))
            // this.setUserInfo(loadUserInfo())
            // console.log('loadConfigStorage(): ' + JSON.stringify(loadConfigStorage()))
            // console.log('loadToken(): ' + loadToken())
            this.setToken(loadToken())
            // console.log('loadUsername(): ' + loadUsername())
            this.setUsername(loadUsername())
            // console.log('loadPassword(): ' + loadPassword())
            this.setPassword(loadPassword())
        },
        /** 根据用户名密码登录 */
        LoginByUsername(userInfo: any) {
            return new Promise((resolve, reject) => {
                uni.$u.$api.LoginApi.authPass(userInfo)
                    .then((res: any) => {
                        const user = res
                        if (user.memberId) this.setVipData(user.memberId)
                        this.setAuthStatus(user.merchantId)
                        this.setToken(user.token)
                        this.setUsername(userInfo.username)
                        if (userInfo.remember) {
                            this.setPassword(userInfo.password)
                        } else {
                            this.setPassword('')
                            this.removePassword()
                        }
                        this.setUserInfo(user)
                        // #ifdef APP-PLUS
                        // 开启socket
                        uni.$u.$imHandler.openSocket()
                        // #endif
                        resolve(res)
                    })
                    .catch((error: any) => {
                        reject(error)
                        console.log(error)
                    })
            })
        },
        LogOut() {
            return new Promise((resolve, reject) => {
                const noticeStore = useNoticeStore()
                const authStore = useAuthStore()
                if (!this.token) {
                    this.clearUserLoginData()
                    authStore.clearData()
                    // 徽标清零
                    noticeStore.clearAllNoticeUnread()
                    // #ifdef APP-PLUS
                    // 关闭socket
                    uni.$u.$imHandler.closeSocket(true)
                    // #endif
                    resolve('')
                } else {
                    uni.$u.$api.LoginApi.authLogout()
                        .then((res: any) => {
                            this.clearUserLoginData()
                            authStore.clearData()
                            // 徽标清零
                            noticeStore.clearAllNoticeUnread()
                            // #ifdef APP-PLUS
                            // 关闭socket
                            uni.$u.$imHandler.closeSocket(true)
                            // #endif
                            resolve(res)
                        })
                        .catch((error: any) => {
                            reject(error)
                        })
                }
            })
        },
        LoginByPhone(data: any) {
            return new Promise((resolve, reject) => {
                uni.$u.$api.LoginApi.authPhone(data)
                    .then((res: any) => {
                        const user = res
                        if (user.memberId) this.setVipData(user.memberId)
                        this.setAuthStatus(user.merchantId)
                        this.setToken(user.token)
                        this.setUsername(user.username)
                        this.setUserInfo(user)
                        resolve(res)
                    })
                    .catch((error: any) => {
                        reject(error)
                    })
            })
        },
        setVipData(id: number | string) {
            return new Promise((resolve, reject) => {
                uni.$u.$api.MemberApi.queryVipinfo({
                    id
                })
                    .then((res: any) => {
                        if (res) {
                            let old = loadConfigStorage()
                            let data = Object.assign(old, {
                                name: res.name,
                                level: res.level
                            })
                            this.setConfig(data)
                            resolve(void 0)
                        }
                    })
                    .catch((err: any) => {
                        reject(err)
                    })
            })
        },
        setAuthStatus(merchantId: number | string) {
            return new Promise((resolve, reject) => {
                uni.$u.$api.MerchantApi.getMerchantStatusById({
                    merchantId: merchantId
                })
                    .then((res: any) => {
                        let old = loadConfigStorage()
                        let data = Object.assign(old, {
                            authStatus: res.authStatus
                        })
                        this.setConfig(data)
                        resolve(void 0)
                    })
                    .catch((err: any) => {
                        reject(err)
                    })
            })
        },
        setToken(token: string) {
            this.token = token
            uni.setStorageSync('cf_app_token', token)
        },
        setUsername(data: string) {
            this.username = data
            uni.setStorageSync('cf_app_username', data)
        },
        removePassword() {
            uni.removeStorageSync('cf_app_password')
        },
        setUserInfo(user: any) {
            this.userInfo = user
            uni.setStorageSync('cf_app_userInfo', JSON.stringify(user))
            uni.$emit('reflash')
        },
        setPassword(password: string) {
            this.password = password || ''
            uni.setStorageSync('cf_app_password', password)
        },
        setConfig(data: any) {
            // console.log('设置 config: ' + data)
            this.config = data
            uni.setStorageSync('cf_app_config', JSON.stringify(data))
        },
        setNickname(name: string) {
            this.userInfo.nickname = name
        },
        setAvatar(url: string) {
            this.userInfo.headPicUrl = url
        },
        updateConfig(para: any) {
            let data = Object.assign(this.config, para)
            this.setConfig(data)
        },
        clearUserLoginData() {
            this.ywyInfo = ''
            this.setToken('')
            this.setUserInfo(undefined)
            this.setConfig({})
            uni.removeStorage({
                key: 'IMDATE'
            })
            useChatStore().updateIMDate(null)
        },
        updateProfile(data: any) {
            data = Object.assign(data, {
                id: this.userInfo.id
            })
            if (data.nickname === undefined) data.nickname = ''
            return new Promise((resolve, reject) => {
                uni.$u.$api.MerchantApi.updateMercantAccountInfo(data)
                    .then((res: any) => {
                        // 修改 store数据
                        // 修改 头像
                        this.userInfo.headPicUrl = data.headPicUrl
                        // 修改昵称
                        this.userInfo.nickname = data.nickname
                        // 修改性别
                        this.userInfo.sex = data.sex

                        resolve(res);
                    })
                    .catch((err: any) => {
                        reject(err);
                    });
            });
        },
        updateDetai(data: any) {
            this.detail = data
        }
    }
})

function loadToken(): string {
    return uni.getStorageSync('cf_app_token')
}

function loadUsername(): string {
    return uni.getStorageSync('cf_app_username')
}

function loadUserInfo(): any {
    let str = uni.getStorageSync('cf_app_userInfo')
    if (str) {
        return JSON.parse(str)
    } else {
        return {}
    }
}

function loadConfigStorage(): any {
    let str = uni.getStorageSync('cf_app_config')
    if (str) {
        return JSON.parse(str)
    } else {
        return {}
    }
}

function loadPassword(): string {
    return uni.getStorageSync('cf_app_password')
}

// function removeToken() {
//     uni.removeStorageSync('cf_app_token')
// }


export default useUserStore
